package com.syt.cellphone.information.http

import android.util.Log
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okio.Buffer
import java.io.IOException
import java.util.*

/**
 * @auther zhulei
 * @date : 2020/9/25 9:21
 * @description : log拦截器
 */
class LogInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        lateinit var newRequestBuild : Request.Builder
        val method = oldRequest.method
        var postBodyString = ""

        if (method.toLowerCase(Locale.ROOT) == "post") {
            when(oldRequest.body) {
                is FormBody -> {
                    val formBodyBuilder = FormBody.Builder()
                    newRequestBuild = oldRequest.newBuilder()
                    val formBody: RequestBody = formBodyBuilder.build()
                    postBodyString = bodyToString(oldRequest.body as FormBody)
                    postBodyString += (if (postBodyString.isNotEmpty()) "&" else "") + bodyToString(
                        formBody
                    )
                    newRequestBuild.post(
                        RequestBody.create(
                            "application/json;charset=UTF-8".toMediaTypeOrNull(),
                            postBodyString
                        )
                    )
                }
                is MultipartBody -> {
                    val oldBodyMultipart = oldRequest as MultipartBody
                    val oldPartList = oldBodyMultipart.parts
                    val builder = MultipartBody.Builder()
                    builder.setType(MultipartBody.FORM)
                    for (part in oldPartList) {
                        builder.addPart(part)
                        postBodyString += (bodyToString(part.body) + "\n")
                    }
                    newRequestBuild = oldRequest.newBuilder()
                    newRequestBuild.post(builder.build())
                    Log.e(TAG, "intercept: ${oldRequest.url}")
                }
                else -> {
                    val formBodyBuilder = FormBody.Builder()
                    newRequestBuild = oldRequest.newBuilder()
                    val formBody = formBodyBuilder.build()
                    postBodyString = oldRequest.body?.let { bodyToString(it) }.toString()
                    postBodyString += (if (postBodyString.isNotEmpty()) "&" else "") + bodyToString(
                        formBody
                    )
                    newRequestBuild.post(
                        RequestBody.create(
                            "application/json;charset=UTF-8".toMediaTypeOrNull(),
                            postBodyString
                        )
                    )
                }
            }
        } else {
            // get请求等
            val commonParamsUrlBuilder = oldRequest.url
                .newBuilder()
                .scheme(oldRequest.url.scheme)
                .host(oldRequest.url.host)
            newRequestBuild = oldRequest.newBuilder()
                .method(oldRequest.method, oldRequest.body)
                .url(commonParamsUrlBuilder.build())
        }
        val newRequest = newRequestBuild.build()
        val t1 = System.nanoTime()
        val response = chain.proceed(newRequest)
        val t2 = System.nanoTime()
        Log.w(TAG, "request \n ${response.request.url} in ${(t2-t1) / 1e6}ms\n content: $postBodyString\n ${response.headers}")
        val mediaType = response.body!!.contentType()
        val content = response.body!!.string()
        Log.w(TAG, "response body: \n $content")
        return response.newBuilder()
            .body(ResponseBody.create(mediaType, content))
            .build()
    }

    companion object {

        private val TAG = "HttpLog"

        private fun bodyToString(request: RequestBody): String {
            return try {
                val buffer = Buffer()
                request.writeTo(buffer)
                buffer.readUtf8()
            } catch (e: IOException) {
                "did not work"
            }
        }

    }
}